/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useState, useRef } from 'react';
import numeral from 'numeral';
import { setLStorage, getLStorage } from '@/utils/utils';

const formatNumeral = (num, format) => numeral(num).format(format);

const Index = props => {
  const { start, format, duration, ratio, cacheInLocal, end, className, ...rest } = props;
  const actionRef = useRef({
    num: 0,
    step: 0,
    timer: 0,
    second: 0,
    cache: {},
    tag: '',
  });

  const [num, updateNum] = useState(0);

  // 记录缓存
  const setCache = () => {
    // eslint-disable-next-line no-shadow
    const { tag, num, second } = actionRef.current;
    if (!tag) return;
    actionRef.current.cache[tag] = { num, second };
    if (cacheInLocal) {
      setLStorage(tag, { num, second, initNum: start[0] });
    }
  };
  // 获取缓存
  const getCache = tag => {
    if (cacheInLocal) {
      return getLStorage(tag) || { num: 0, second: 0 };
    }
    return actionRef.current.cache[tag] || { num: 0, second: 0 };
  };

  const handleClean = () => {
    clearTimeout(actionRef.current.timer);
  };

  // 获取随机步长
  const getRandomStep = step => {
    const steps = [0, 0, step / 3, step / 2, step];
    // eslint-disable-next-line radix
    return parseInt(steps[parseInt(Math.random() * steps.length)]);
  };

  // 更新数据
  const triggerUpdateNumber = () => {
    // eslint-disable-next-line no-shadow
    const { num, step } = actionRef.current;
    // 兼容驿站大屏跳动数字
    const maxNum = end || start[0];
    let current = num + getRandomStep(Math.max(step, 5));
    if (current >= maxNum || actionRef.current.second >= duration) {
      // 已达到最大值 或 已达到最大时间，更新为最大值
      current = maxNum;
      actionRef.current.second = 0;
    } else {
      // 循环
      actionRef.current.second += 1;
      actionRef.current.timer = setTimeout(() => {
        triggerUpdateNumber();
      }, 1000);
    }
    actionRef.current.num = current;
    updateNum(current);
    setCache();
  };

  useEffect(
    () => {
      // eslint-disable-next-line no-shadow
      const [num, tag] = start;
      if (num >= 0) {
        const { num: cacheNum, second: cacheSecond, initNum } = getCache(tag);
        actionRef.current.tag = tag;
        actionRef.current.second = cacheSecond;
        actionRef.current.num = cacheNum;

        if (actionRef.current.num === 0 || initNum != num) {
          // 更新初始值
          actionRef.current.num = parseInt(num * ratio, 10);
        }
        // 每秒应增加数字
        actionRef.current.step = Math.max(
          0,
          (num - actionRef.current.num) / (duration - actionRef.current.second),
        );
        triggerUpdateNumber();
      }

      return () => {
        handleClean();
      };
    },
    [start],
  );

  return (
    <span className={className} {...rest}>
      {formatNumeral(num, format)}
    </span>
  );
};

Index.defaultProps = {
  start: [0],
  format: '0,0',
  duration: 10 * 60,
  ratio: 0.7, // 初始比例
  cacheInLocal: false, // 缓存数据到本地
  end: null, // 结束的值（新零售大屏兼容）
};

export default Index;
